package com.zhq.blog.manage.domain.controller.system;



import javax.validation.Valid;

import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhq.blog.core.domain.system.Notice;
import com.zhq.blog.manage.domain.controller.BaseController;
import com.zhq.blog.manage.domain.controller.BossModel;

@Controller
@Scope("prototype")
@RequestMapping("/admin/system/notice/*")
public class NoticeController extends BaseController {
	
	@RequestMapping()
    public BossModel index(@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
			return createModel("admin/system/notice/list").add("noticePage",context.getNoticeRepository().findAll(pageable));
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		return createModel("admin/system/notice/info").add("notice",new Notice());
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("admin/system/notice/info").add("notice",context.getNoticeRepository().findOne(id));
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		context.getNoticeRepository().delete(id);
		return createModel("admin/system/notice/notice_table").add("noticePage",context.getNoticeRepository().findAll(pageable));
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	@InitBinder(value = { "name", "display", "content" })
	public BossModel save(@Valid final Notice notice, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectPrizes,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		if (bindingResult.hasErrors()) {
			return createModel("admin/system/notice/info");
		}
		context.getNoticeRepository().save(notice);
		String message = notice.getSucessFlashMessage();
		redirectPrizes.addFlashAttribute("message", message);
		return createModel("redirect:/admin/system/notice/index");
	}

}
